package com.demo.mqtt.zigbee.handeler.upload;

import com.demo.mqtt.common.client.MqttConnectionUtils;
import com.demo.mqtt.common.utils.HexConvertUtil;
import com.demo.mqtt.zigbee.entity.po.eigenUpload.EigenUpLoadPO;
import com.demo.mqtt.zigbee.entity.po.eigenUpload.EigenUpLoad;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @program: mqtt
 * @description: 特征值上传
 * @author: liuYunKai
 * @create: 2021-03-24 14:56
 */
@Slf4j
@Component
public class FeaturesDataUpload {
    @Autowired
    private MqttConnectionUtils mqttConnectionUtils;
    @Autowired
    private MongoTemplate mongoTemplate;

    public boolean annalyze(String topic, String hesStr, String command, MqttMessage mqttMessage) {
        if (!"20".equalsIgnoreCase(command)) {
            return false;
        }

        //数据内容有可能不定长，所以直接采用截取的方式
        String contextStr = hesStr.substring(32, hesStr.length() - 4);

        //按字节解析
        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeBytes(HexConvertUtil.hexStrToByteArrs(contextStr));

        EigenUpLoad eigenUpLoad = new EigenUpLoad();
        ByteBuffer buffer = ByteBuffer.wrap(mqttMessage.getPayload());
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        eigenUpLoad.setByteBuffer(buffer, 0);

        EigenUpLoadPO po = new EigenUpLoadPO(eigenUpLoad,byteBuf);


        long count = mongoTemplate.count(
                new Query(
                        Criteria
                                .where("sn").is(po.getSn())
                                .and("eigenDate").is(po.getEigenDate())
                                .and("eigenTime").is(po.getEigenTime())
                                .and("paramDate").is(po.getParamDate())
                                .and("paramTime").is(po.getParamTime())

                ), EigenUpLoadPO.class);
        // 发送mq报警
        if (count == 0) {
            //发送mq报警
//            asyncTaskService.pushNbAlarmEvent(po);
            //保存数据
            mongoTemplate.save(po);
        } else {
            log.info("重复调用");
        }
        return true;
    }
}
